const db = require('../db/index')
const bcrypt = require('bcryptjs')

// 获取用户基本信息的处理函数
exports.getUserInfo = (req,res)=>{
	console.log(req.user)
	const sql='select user_id,username,nickname,emailId,user_pic from ev_users where user_id=?'
	console.log(req.user.user_id)
	// 解析成功会挂载到req
	db.query(sql,req.user.user_id,(err,results)=>{
		if(err) return res.cc(err)
		if(results.length!==1) return res.cc('获取用户信息失败！')
		res.send({
			status:0,
			message:'获取用户信息成功！',
			data:results[0]
		})
	})
}
// 修改用户信息
exports.updateUserInfo = (req,res)=>{
	console.log(req.user)
	const sql = 'update ev_users set ? where user_id=?'
	console.log(req.body)
	db.query(sql,[req.body,req.body.user_id],(err,results)=>{
		if(err)return res.cc(err)
		if(results.affectedRows!=1)return res.cc('修改用户信息失败！')
		// 修改用户信息成功
		return res.cc('修改用户信息成功！',0)
	})
}
// 重置密码
exports.updatePassword = (req,res)=>{
	console.log(req.user)
	const sql = `select * from ev_users where user_id=?`
	db.query(sql,req.user.user_id,(err,results)=>{
		if(err) return res.cc(err)
		if(results.length!==1)return res.cc('用户不存在！')
		const compareResult = bcrypt.compareSync(req.body.oldPwd,results[0].password)
		if(!compareResult) return res.cc('旧密码输入错误！')
		const updatePwdsql = 'update ev_users set password=? where user_id=?'
		console.log(req.body)
		let newPwd=bcrypt.hashSync(req.body.newPwd,10)
		db.query(updatePwdsql,[newPwd,req.user.user_id],(err,result)=>{
			if(err)return res.cc(err)
			if(result.affectedRows!=1)return res.cc('修改密码失败！')
			// 修改用户信息成功
			return res.cc('修改密码成功！',0)
		})
	})
}
// 修改头像
exports.updateAvater=(req,res)=>{
	console.log(req.user)
	const sql = 'update ev_users set user_pic=? where user_id=?'
	db.query(sql,[req.body.avatar,req.user.user_id],(err,results)=>{
		if(err)return res.cc(err)
		if(results.affectedRows!==1)return res.cc('更新头像失败！')
	})
	res.cc('更新头像成功！',0)
}